//
//  RequestTool.m
//  PgyHelper
//
//  Created by 鹏鹏 on 2020/11/12.
//  Copyright © 2020 CleverPeng. All rights reserved.
//

#import "RequestTool.h"

@implementation RequestTool

+ (void)postWith:(NSString *)urlString paramsString:(NSString *)paramsString completeHandler:(void (^)(NSString * _Nullable, NSDictionary * _Nullable, BOOL, NSString * _Nullable))completeHandler {

    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [mutableRequest setHTTPMethod:@"POST"];
    [mutableRequest setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [mutableRequest setHTTPBody:[paramsString dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLSession *session = [NSURLSession sharedSession];

    NSLog(@"\n=================\n发起请求: %@, 参数: %@", urlString, paramsString);
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {


        if(error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completeHandler(nil, nil, NO, @"网络请求失败");
            });
            return;
        }

        [RequestTool parasResponse:data completeHandler:^(NSString * _Nullable responseString, NSDictionary * _Nullable responseDataDic, BOOL isSuccess, NSString * _Nullable message) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if(error) {
                    completeHandler(responseString, nil, NO, @"网络请求失败");
                    return;
                }
                completeHandler(responseString, responseDataDic, isSuccess, message);
            });
        }];
    }];
    [dataTask resume];
}

+ (void)parasResponse:(NSData *)data completeHandler:(void (^)(NSString * _Nullable, NSDictionary * _Nullable, BOOL, NSString * _Nullable))completeHandler {
    if (nil == data) {
        completeHandler(nil, nil, NO, @"空数据");
    }
    NSString *returnDataStr = [NSString stringByReplaceUnicode:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];

        // 解析
    NSError *readError = nil;
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&readError];
    
    NSError *prettyError;
    NSData *prettyData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingSortedKeys | NSJSONWritingPrettyPrinted | NSJSONWritingWithoutEscapingSlashes error:&prettyError];
    NSLog(@"\n=================\n请求返回: \n%@", [[NSString alloc] initWithData:prettyData encoding:NSUTF8StringEncoding]);

    if (readError) {
        completeHandler(returnDataStr, nil, NO, @"数据解析失败");
        return;
    }

    if ([dictionary[@"code"] intValue] == 0) {
        NSDictionary *dic = dictionary[@"data"];
        completeHandler(returnDataStr, dic, YES, @"");
        return;
    } else {
        completeHandler(returnDataStr, nil, NO, @"请求失败");
        return;
    }
}

+ (NSString *)get_api_key {
    NSString *api_key = [[NSUserDefaults standardUserDefaults] valueForKey:KEY_API_KEY];
    return api_key;
}
+ (NSString *)reset_api_key {
    [RequestTool save_api_key:@""];
    return [RequestTool get_api_key];
}
+ (BOOL)save_api_key:(NSString *)api_key {
    [[NSUserDefaults standardUserDefaults] setValue:api_key forKey:KEY_API_KEY];
    return [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
